﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Baosight.ZNH.ZMCommon;
using Baosight.Platform.Core;
using Baosight.Platform.Core.ServiceModel;
using Baosight.Platform.Core.UI.Controls;
using Telerik.Windows.Controls;
using Baosight.ZNH.ZMCommon.ChildWindows;
using Baosight.ZNH.ZMCM.UI.Utils;
using System.Windows.Browser;


namespace Baosight.ZNH.ZMCM.UI
{
    /// <summary>
    /// 初始数据主表  
    /// </summary>
    /// Title:ZMCM80
    /// Copyright:Baosight Software LTD.co Copyright (c) 2011
    /// Company:上海宝信软件股份有限公司
    /// Author: 张坤
    /// Version: 1.0
    /// History:
    ///       2010-12-14  张坤   [创建]
    ///
    public partial class ZMCM80 : EFViewCmes
    {
        private DepotBlock depotBlock = new DepotBlock();//构造前台下拉列表
        
        public ZMCM80()
        {
            InitializeComponent();
        }

        public override void Initialize(EIInfo initData)
        {
            initData.AddBlock(depotBlock.GetDepotStatus());
            base.Initialize(initData);
        }

        #region 根据主表选中信息，刷新从表
        /// <summary>
        /// 选中主表一条记录，显示该条记录的从表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grid_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (null != this.grid.SelectedItem)
            {
                this.container.Visibility = Visibility.Visible;
                var fdApplicationId = this.grid.SelectedItem.GetType().GetProperty("fdKeyId").GetValue(this.grid.SelectedItem, null);
                var fdApplicationDepartment = this.grid.SelectedItem.GetType().GetProperty("fdApplicationDepartment").GetValue(this.grid.SelectedItem, null);
                var fdStatus = this.grid.SelectedItem.GetType().GetProperty("fdApplicationStatus").GetValue(this.grid.SelectedItem, null);
                var fdYear = this.grid.SelectedItem.GetType().GetProperty("fdYear").GetValue(this.grid.SelectedItem, null);
                var fdMonth = this.grid.SelectedItem.GetType().GetProperty("fdMonth").GetValue(this.grid.SelectedItem, null);

                Dictionary<string, string> args = new Dictionary<string, string>();
                args.Add("fdApplicationId", fdApplicationId.ToString());
                args.Add("fdApplicationDepartment", fdApplicationDepartment.ToString());
                args.Add("fdStatus", fdStatus.ToString());
                args.Add("fdYear", fdYear.ToString());
                args.Add("fdMonth", fdMonth.ToString());
                this.container.LoadView("ZMCM81", args);
            }
            else
            {
                this.container.Content = null;
            }
        }
        #endregion

        #region 根据从表返回信息，刷新主表
        /// <summary>
        ///根据从表界面修改信息刷新页面
        /// </summary>
        public override void OnEIDataPublished(Platform.Core.EIInfo data)
        {
            
            if (null != this.grid.SelectedItem)
            {
                EIInfo info = new EIInfo();
                info.Attributes.Add(EIConstants.ServiceNameKey, "ZMCM80");
                info.Attributes.Add(EIConstants.MethodNameKey, "query");

                EIBlock block = info.AddBlock(EIConstants.QueryStatusBlock);

                EIColumn column = new EIColumn();
                column.Name = "fdKeyId";
                block.AddColumn(column);

                EIRow _row = (this.grid.SelectedItem as UIBaseEntity).GetEIRow();
                EIRow row = new EIRow();
                row.Add("fdKeyId", _row["fdKeyId"]);
                block.AddRow(row);
                info.AddBlock(block);
                info.AddBlock(EIConstants.ResultBlock).Set(EIConstants.ShowCount, "true");

                IServiceAgent service = new HttpServiceAgent();
                service.CallService(info, OnCallChildServiceCompleted);

            }
        }

        /// <summary>
        /// 刷新主表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnCallChildServiceCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo == null || e.EIInfo.GetStatus() == -1)
            {
            }
            else
            {
                EIRow row = (this.grid.SelectedItem as UIBaseEntity).GetEIRow();
                row["fdApplicationSum"] = e.EIInfo.GetBlock(EIConstants.ResultBlock).Get(0, "fdApplicationSum");
            }
        }
        #endregion

        #region 新增、删除操作
        /// <summary>
        /// 主表新增操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnInsertButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            EIInfo inInfo = new EIInfo();
            inInfo.Attributes.Add(EIConstants.ServiceNameKey, "ZMCM82");
            inInfo.Attributes.Add(EIConstants.MethodNameKey, "initLoad");

            HttpServiceAgent agent = new HttpServiceAgent();
            agent.CallService(inInfo, DoWorkComplete);
            
            //this.Shell.LoadView("ZMCM82", null);
            //base.TempButtonOpen(true);//按钮生效
        }

        private void DoWorkComplete(object sender, DoWorkCompletedEventArgs e)
        {
            OpenImportPopup(e.EIInfo, "领料申请管理-新增领料", "insert", null);
        }

        /// <summary>
        /// 构造入库页面内容、弹出页面
        /// </summary>
        /// <param name="eIInfo"></param>
        /// <param name="title"></param>
        private void OpenImportPopup(EIInfo _eIInfo, string _title, string _dialogType, string _args)
        {
            ZMCM82 exportApplication = new ZMCM82();//构造一个新的修改页面
            exportApplication.EIDataContext = new Platform.Core.UI.EIDataContext();
            exportApplication.Initialize(_eIInfo);

            CmesWindows _popup = new CmesWindows();//构造一个弹出页面
            _popup.WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation.CenterOwner;
            _popup.TopOffset = -150;
            _popup.LeftOffset = -80;
            _popup.ResizeMode = ResizeMode.NoResize;//设置不能修改窗口大小
            _popup.Header = _title == null ? "" : _title;//设置Title
            _popup.Content = exportApplication;//让新增页面在弹出窗口显示
            _popup.Closed += new EventHandler<WindowClosedEventArgs>(CmesWindow_Closed);

            _popup.ShowDialog();//模态显示弹出窗口
        }

        /// <summary>
        /// 弹出窗口关闭时执行的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmesWindow_Closed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == true)
            {
                this.grid.Refresh();//刷新Grid区域
                this.UpdateHomePageData(new EIInfo());//发布数据
            }

            //按钮生效
            base.TempButtonOpen(true);

            //超链接生效
            if (base.TempHyperlink != null)
            {
                base.TempHyperlink.IsEnabled = true;
                base.TempHyperlink = null;
            }
        }

        /// <summary>
        /// 删除方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void OnDeleteButtonClick(object sender, RoutedEventArgs e)
        {
            EFViewCmesProperty _view = new EFViewCmesProperty();
            _view.EFGridCheckedRows = this.grid.GetCheckedEIRows();
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;

            IList<EIRow> _list = this.grid.GetCheckedEIRows() == null ? new List<EIRow>() : this.grid.GetCheckedEIRows();
            bool canDelete = true;
            String msg = "";
            if (_list.Count <= 0)
            {
                msg = "请选择要删除的记录(一条或多条)！";
                canDelete = false;
            }
            else
            {
                for (int i = 0; i < _list.Count; i++)
                {
                    if (this.grid.GetCheckedEIRows()[i]["fdApplicationStatus"].ToString().Equals("上报"))
                    {
                        msg = "选择的记录包含有上报的记录，不允许删除！";
                        canDelete = false;
                        break;
                    }
                    if (this.grid.GetCheckedEIRows()[i]["fdApplicationStatus"].ToString().Equals("已审批"))
                    {
                        msg = "选择的记录包含有已审批的记录，不允许删除！";
                        canDelete = false;
                        break;
                    }
                }
            }
            if (canDelete)
            {
                base.ViewProperty = _view;
                base.OnDeleteButtonClick("ZMCM80", "delete", sender, e);
                base.TempButtonOpen(true);//按钮生效
            }
            else
            {
                this.OpenEFWindowAlert(msg, true);
                return;
            }
        }   
        #endregion

        #region 上报操作
        /// <summary>
        /// 上报操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnApproveButtonClick(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            button.IsEnabled = false;
            TempButton = button;

            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择需上报的领料申请！", true);
                return;
            }
            else
            {
                for (int i = 0; i < count; i++ )
                {
                    if (this.grid.GetCheckedEIRows()[i]["fdApplicationStatus"].ToString().Equals("上报"))
                    {
                        this.OpenEFWindowAlert("不能重复上报申请记录！", true);
                        return;
                    }
                    if (this.grid.GetCheckedEIRows()[i]["fdApplicationStatus"].ToString().Equals("已审批"))
                    {
                        this.OpenEFWindowAlert("不能上报已审批的申请记录！", true);
                        return;
                    }
                }

                DialogParameters param = this.ModelDialogParameters("Confirm", "确定上报该申请记录？");
                param.Closed = OnApproveConfirmClosed;
                EFWindow.Confirm(param);
            }
        }

        /// <summary>
        /// 上报确认，点击上报按钮执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnApproveConfirmClosed(object sender, WindowClosedEventArgs e)
        {
            if (e.DialogResult == null || !e.DialogResult.Value)
            {
                this.TempButtonOpen(true);//取消后，按钮生效
                return;
            }
            if (e.DialogResult.Value)
            {
                base.Submit(OperationMode.Update, "ZMCM80", "Approve", DataRange.CheckedItems, DoCommitCompleted, null);
            }
        }
        /// <summary>
        /// 执行完上报操作的回调函数
        /// </summary>
        public override void DoCommitCompleted(object sender, DoWorkCompletedEventArgs e)
        {
            if (e.EIInfo.Status == -1)
            {
                String msg = "插入失败！";
                if (e.EIInfo.GetMsg() != null || e.EIInfo.GetMsg().Equals(""))
                {
                    msg = e.EIInfo.Msg;
                }
                base.OpenEFWindowAlert(msg, true);
                base.TempButtonOpen(true);
            }
            else
            {
                this.grid.Refresh();
                base.TempButtonOpen(true);//按钮生效
            }
        }
        #endregion
        #region 打印领料单操作
        /// <summary>
        /// 打印入库单操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnPrintButtonClick(object sender, RoutedEventArgs e)
        {
            //按钮失效
            Button _button = sender as Button;
            _button.IsEnabled = false;
            base.TempButton = _button;
            int count = this.grid.GetCheckedEIRows().Count;
            if (count <= 0)
            {
                this.OpenEFWindowAlert("请选择一条记录进行打印！", true);
                return;
            }
            else if (count != 1)
            {
                this.OpenEFWindowAlert("只能选择一条记录进行打印！", true);
                return;
            }
            //else
            //{
            //    if (!this.grid.GetCheckedEIRows()[0]["fdApplicationStatus"].ToString().Equals("已审批"))
            //    {
            //        this.OpenEFWindowAlert("只能打印已审批的记录！", true);
            //        return;
            //    }
            //}
            string fdKeyId = "'" + this.grid.GetCheckedEIRows()[0]["fdKeyId"].ToString() + "'";
            Uri uri = Uploader.ConstructAbsoluteUri("../admin/RunmaxReport.jsp?projectName=CMESReport&reportName=ExportApplication&KeyId=" + fdKeyId);
            HtmlPage.Window.Navigate(uri, "_blank");
            base.TempButtonOpen(true);//按钮生效
        }
        #endregion
    }

     
}
